package observer

type Subject interface {
	RegisterObserver(ob Observer)
	RemoveObserver(ob Observer)
	notifyObservers()
}

type SubjectImpl struct {
	//保存订阅的观察者
	observers []*Observer
	//状态
	status int
}

func CreateSubjectImpl() *SubjectImpl {
	return new(SubjectImpl)
}

func (sj *SubjectImpl) RegisterObserver(ob Observer) {
	sj.observers = append(sj.observers, &ob)
}

func (sj *SubjectImpl) RemoveObserver(ob Observer) {
	//找要删除的位置
	targetPos := -1
	for position, observer := range sj.observers {
		if (*observer).getId() == ob.getId() {
			targetPos = position
			break
		}
	}
	if targetPos >= 0 {
		sj.observers = append(sj.observers[:targetPos], sj.observers[targetPos+1:]...)
	}
}

func (sj *SubjectImpl) notifyObservers() {
	for _, ob := range sj.observers {
		//挨个通知
		(*ob).notified(sj.status)
	}
}

func (sj *SubjectImpl) SetData(status int) {
	sj.status = status
	sj.notifyObservers()
}
